package com.vonchenchen.photodemo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vonchenchen.photodemo.MainActivity;
import com.vonchenchen.photodemo.MyApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by vonchenchen on 2015/12/11 0011.
 */
public class ImageLoaderManager {

    private static String DOCUMENT_PATH = "/vonchenchen/";

    //ImageView 的文件缓存
    public final static String FILE_IMAGELOADER_CACHE = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + DOCUMENT_PATH + "image/";

    //保存裁剪后照片的路径
    public final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + DOCUMENT_PATH + "Portrait/";

    //保存直接拍照后未经剪裁照片的路径
    public final static String FILE_SAVEPATH_CAMERA = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + DOCUMENT_PATH + "Camera/";

    //保存经过模糊处理后的图片路径
    public final static String FILE_SAVEPATH_FUZZY = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + DOCUMENT_PATH + "Fuzzy/";

    //使用ImageLoader下载后需要上传的图片，单独拷贝到这个目录下，并将文件名修改为相应的格式
    public final static String FILE_SAVEPATH_UPLOAD = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + DOCUMENT_PATH + "Upload/";

    //裁剪后照片的前缀名  文件名：FILE_SAVENAME + timeStamp + ".jpg"
    public final static String FILE_SAVENAME_CROP = "vonchenchen";
    //直接拍照后照片的前缀名   文件名：FILE_SAVENAME_CAMERA + timeStamp + ".jpg"/other
    public final static String FILE_SAVENAME_CAMERA = "vonchenchen";

    public final static String FILE_SAVENAME_UPLOAD = "vonchenchen";

    private static Context mCtx;

    /** 记录用于选取头像的路径 */
    static String recordPath = "";

    /**
     * 将图片从ImageLoader的硬盘缓存路径拷贝到上传路径，并指定新的文件名
     * 复制成功返回复制的文件
     * @param path     源路径
     * @param newName  我们指定的文件名
     */
    public static File copyToUpLoadFileAndRename(String path, String newName){
        File src = new File(path);

        if(!src.exists()){
            return null;
        }
        File des = new File(ImageLoaderManager.FILE_SAVEPATH_UPLOAD + newName);

        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = ImageLoaderManager.FILE_SAVEPATH_UPLOAD;
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        if(copyToAnotherDocument(src, des) != -1){
            return des;
        }else{
            return null;
        }
    }

    /**
     * 将一个文件拷贝到指定文件目录下，并修文件名
     * @param src
     * @param des
     */
    private static int copyToAnotherDocument(File src, File des){
        //long time=new Date().getTime();
        int length=1024*10;
        try {
            FileInputStream in=new FileInputStream(src);
            FileOutputStream out=new FileOutputStream(des);
            byte[] buffer=new byte[length];
            while(true){
                int ins=in.read(buffer);
                if(ins==-1){
                    in.close();
                    out.flush();
                    out.close();
                    //return new Date().getTime()-time;
                    return 1;
                }else
                    out.write(buffer,0,ins);
            }
        }catch (Exception e){
            System.out.print(e.toString());
        }finally {
        }
        return -1;
    }

    /**
     * 获取ImageLoader的硬盘缓存中对应的路径
     * @param uriStr      图片资源uri
     * @param generator   给图片设置名字的generator，需要和config的config中设置的generator一样
     * @return
     */
    public static String getImageLoaderDiskCacheImageName(String uriStr, FileNameGenerator generator){
        String name = generator.generate(uriStr);
        String path = ImageLoaderManager.FILE_IMAGELOADER_CACHE + name;
        return path;
    }

    public static void createDir(String dir){
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = dir;
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }
    }

    /**
     * 将硬盘缓存中的图片拷贝到我们指定的文件
     * @param uriStr
     * @return
     */
    public static String saveImageInOurDocument(String uriStr, String name){

        //获取图片在硬盘缓存上的路径
        String path = ImageLoaderManager.getImageLoaderDiskCacheImageName(uriStr, new HashCodeFileNameGenerator());
        //System.out.print(path);

        //将图片从ImageView维护的硬盘缓存中取出，拷贝到我们指定的路径下
        File file = ImageLoaderManager.copyToUpLoadFileAndRename(path, name + ".jpg");
        if(file!=null) {
            //获取当前图片，这种常用于下载后上传，需要知道图片路径
            String uploadPath = file.getAbsolutePath();
        }else{

            //configuration.diskCache.get(this.uri)
            //如果本地缓存被删除
            //Toast.makeText(MainActivity.this, "photo is not in diskcache", Toast.LENGTH_SHORT).show();

            ImageLoader.getInstance().getDiskCache().remove(uriStr);
            ImageLoader.getInstance().getMemoryCache().remove(uriStr);
            return null;
        }

        return path;
    }

    /**
     * 将Bitmap写入文件
     * @param bmp
     * @param name  图片文件名,不用加后缀
     */
    public static Uri saveCroppedImage(Bitmap bmp, String name) {

        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = ImageLoaderManager.FILE_SAVEPATH_FUZZY;
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        File file;
        file = new File(ImageLoaderManager.FILE_SAVEPATH_FUZZY + name +".jpg");
        Uri ret = Uri.fromFile(file);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 清除一个路径下中所有的文件
     * @param path
     */
    public static void clearDocument(String path){
        File file = new File(path);
        if(!file.exists()){
            return ;
        }

        for(File f: file.listFiles()){
            f.delete();
        }
    }

    /**
     * 获取模糊图，如果本地有加载本地，否则对本地图片处理后保存并加载
     * @param protraitPath
     * @param imageName
     * @param imageView
     * @param options
     */
    public static void loadBlurImage(String protraitPath, String imageName,ImageView imageView, DisplayImageOptions options){

        //指定要获取照片的名字字段
        String name = imageName;
        //构造指定图片的文件uri
        File file;
        file = new File(ImageLoaderManager.FILE_SAVEPATH_FUZZY + name +".jpg");
        Uri uri = Uri.fromFile(file);
        String uriStr = uri.toString();

        //由本地获取模糊图片
        if(file.exists() && recordPath.equals(protraitPath)){
            ImageLoader.getInstance().displayImage(uriStr, imageView);

            Toast.makeText(MyApplication.getContext(), "local loaded!", Toast.LENGTH_SHORT).show();
        }else if(!TextUtils.isEmpty(protraitPath)){

            //获取正常图片做处理
            //解压图片
            Bitmap protraitBitmap = ImageUtils.convertToBitmap(protraitPath, 200, 200);
            //将位图进行处理
            protraitBitmap = BlurUtil.blurBitmap(protraitBitmap, MyApplication.getContext());
            //将处理结果压缩为名字为 test.jpg的 jpeg格式文件，写入指定文件
            ImageLoaderManager.saveCroppedImage(protraitBitmap, name);

            ImageLoader.getInstance().displayImage(uriStr, imageView, options);

            Toast.makeText(MyApplication.getContext(), "fuzzy.........", Toast.LENGTH_SHORT).show();

            recordPath = protraitPath;
        }
    }
}
